//
//  KKConversationManager.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/23.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKConversationManager.h"

#import "RAChatKit/RAMessage.h"
#import "KKConversationItem.h"
#import "KKNetworkRequest+V1.h"
#import "KKMessageItem.h"

@interface KKConversationManager() {
    
    NSMutableArray *arr_conversationItems;      //所有会话对象
}

@end

@implementation KKConversationManager

+ (instancetype)defaultManager {
    static KKConversationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKConversationManager new];
    });
    return manager;
}

//  发送获取所有会话请求
+ (void)sendAllConversationItemsRequest:(KKConversationRequestSuccessBlockHandle)success {
    
    KKNetworkRequest *request = [KKNetworkRequest request_getChatItems];
    [KKNetworking sendRequest: request responseCallBack:^(id response, NSString *error) {
        
        if (error) {
            if (success) {
                success(false,error);
            }
            return;
        }
        
        NSMutableArray *arr_conversationItems = [NSMutableArray array];
        
        if ([response isKindOfClass: [NSArray class]]) {
            //  解析会话对象列表
            NSArray *tmpArray = (NSArray*)response;
            for (NSDictionary *tmpItem in tmpArray) {
                KKConversationItem *item = [KKConversationItem itemWithJson: tmpItem];
                [arr_conversationItems addObject: item];
            }
        }
        
        //
        [KKConversationManager defaultManager]->arr_conversationItems = arr_conversationItems;
        
        if (success) {
            success(true,arr_conversationItems);
        }
    }];
}


+ (void)receiveNewMessage:(NSDictionary*)newMessage {
    
    if (![newMessage isKindOfClass: [NSDictionary class]]) {
        return;
    }
    
    NSInteger badge = [newMessage[@"badge"] intValue];
    NSDictionary *fr = newMessage[@"fr"];
    NSDictionary *message = newMessage[@"message"];
    NSTimeInterval timestamp = [newMessage[@"timestamp"] doubleValue];
    
    NSString *chatId = newMessage[@"thread"];
    
    KKConversationManager *manager = [KKConversationManager defaultManager];
    
    KKConversationItem *currentItem = manager.currentItem;
    
    if (currentItem != nil) {
        
        if ([chatId isEqualToString: currentItem.identifier]) {
            //  表示当前接收到的消息正是当前会话对象者发送的消息
            
            NSMutableDictionary *tmpDictionary = [NSMutableDictionary dictionaryWithDictionary: message];
            [tmpDictionary setObject: fr forKey: @"fr"];
            [tmpDictionary setValue: @(timestamp) forKey: @"timestamp"];
            RAMessage *message = [RAMessage itemWithJson: tmpDictionary];
            [currentItem receiveMessage: [KKMessageItem msgWithTMessage: message]];
            return;
        }
    }
    else {
        for (KKConversationItem *item in manager->arr_conversationItems) {
            if ([chatId isEqualToString: item.identifier]) {
                //  表示当前接收到的消息正是当前会话对象者发送的消息
                NSMutableDictionary *tmpDictionary = [NSMutableDictionary dictionaryWithDictionary: message];
                [tmpDictionary setObject: fr forKey: @"fr"];
                [tmpDictionary setValue: @(timestamp) forKey: @"timestamp"];
                
                item.badge = badge;
                
                RAMessage *message = [RAMessage itemWithJson: tmpDictionary];
                [item receiveMessage: [KKMessageItem msgWithTMessage: message]];
                
                return;
            }
        }
        
        //  如果本地的会话组中无该会话对象的信息则应该新增一个
        
        NSMutableDictionary *tmpDictionary = [NSMutableDictionary dictionary];
        [tmpDictionary setObject: chatId forKey: @"id"];
        [tmpDictionary setObject: fr forKey: @"customer"];
        
        NSMutableDictionary *lastMessageInfo = [NSMutableDictionary dictionaryWithDictionary: message];
        [lastMessageInfo setValue: @(timestamp) forKey: @"timestamp"];
        [tmpDictionary setObject: lastMessageInfo forKey: @"lastMessage"];
        
        KKConversationItem *item = [KKConversationItem itemWithJson: tmpDictionary];
        item.badge = badge;
        [manager->arr_conversationItems addObject: item];
        
        if (manager.numberUpdateHandle != nil) {
            manager.numberUpdateHandle(manager->arr_conversationItems);
        }
    }
}

+ (void)removeItem:(KKConversationItem*)item {
    if ([[KKConversationManager defaultManager]->arr_conversationItems containsObject: item]) {
        [[KKConversationManager defaultManager]->arr_conversationItems removeObject: item];
    }
}

@end
